package model.service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import Hibernate.dao.FinalScore;
import Hibernate.dao.FinalScoreDAO;
import Hibernate.dao.Score;
import Hibernate.dao.ScoreDAO;


public class CalculateScoreService {
	
		Map<String,String> map;
		ScoreDAO scoreDao;
		FinalScoreDAO finalScoreDao;
		
		public void setScoreDao(ScoreDAO scoreDao) {
			this.scoreDao = scoreDao;
		}

		public void setFinalScoreDao(FinalScoreDAO finalScoreDao) {
			this.finalScoreDao = finalScoreDao;
		}

		//读取score数据，将同一userInfo的firstscore,finalscore取到，算平均值，找到final_score中的userid，存入数据
		public String calculateScore(String userInfo){
			map = new HashMap<String,String>();
			List finalScoreList = finalScoreDao.findAll();
			if(finalScoreList.size() == 0)
			{
				map.put("flag", "false");
				map.put("reason","final_score没找到该考生号数据");
				return map.toString();
			}else {
					do{	
						map = new HashMap<String,String>();//一条数据
				//取final_score中的userId,找到score中的userId相同的所有记录
						FinalScore tempFinalScore = (FinalScore)finalScoreList.get(0);
						List scoreList = scoreDao.findByUserId(tempFinalScore.getUserId());//所有userId相同的score记录
						if(scoreList.size() == 0)
						{
							map.put("flag", "false");
							map.put("reason", "找不到该考生成绩");
							return map.toString();
						}
						map.put("flag", "true");
						map.put("userId",tempFinalScore.getUserId());
						map.put("examId",tempFinalScore.getExamId());
						
						double[] firstScore = new double[10];//假设最多10条数据.
						double[] finalScore = new double[10];
						int index =0;
				//计算
						do{
							Score tempScore = (Score) scoreList.get(0);
							firstScore[index]= Double.valueOf(tempScore.getFirstScore());
							finalScore[index]= Double.valueOf(tempScore.getFinalScore());
							index++;
							scoreList.remove(0);
						}while(scoreList.size() > 0 );
						double temp_firstScore=0.0, temp_finalScore=0.0;
						for(int i = 0 ;i < index ;i++)
						{
							temp_firstScore += firstScore[i];
							temp_finalScore += finalScore[i];
						}
						map.put("firstScore", Double.toString((temp_firstScore)/index));
						map.put("finalScore", Double.toString((temp_finalScore)/index));
						
				//修改final_score中的userId相同的数据		
						tempFinalScore.setFirstScore(Double.valueOf(map.get("firstScore")));
						tempFinalScore.setFinalScore(Double.valueOf(map.get("finalScore")));
						finalScoreDao.attachDirty(tempFinalScore);
						System.out.print(map.toString());
						finalScoreList.remove(0);
					}while(finalScoreList.size() > 0);//所有考生的成绩都计算完成
				
				
			}
						
			return map.toString();
		}
}
